import { forward } from './router';
import env from '@/config/env';
import ResponseData = Http.ResponseData;
import {getCommonParams} from '@/config/commonParams';
import {APP_ID} from "@/config/app";
import {loginOut} from "@/hooks/user";

function reject(err: { errno: number; errmsg: string }) {
  const { errmsg = '系统无响应，请稍后再试', errno = -1 } = err;
  switch (errno) {
    case 10000:
      // 特殊异常处理
      forward('login');
      break;

    default:
      uni.showToast({title: errmsg, icon: 'error'});
      break;
  }
}

const apiBaseUrl = env.VUE_APP_BASE_URL + env.VUE_APP_DEFAULT_SHENYU_CONTEXT_PATH

function baseRequest(
  method: Http.Method,
  url: string,
  data,
) {
	const _data = Object.fromEntries(
			Object.entries(data).filter(([key, value]) => value !== undefined)
	)
  return new Promise((resolve) => {
    let responseData: ResponseData;
	  const accessToken = uni.getStorageSync('token')
    uni.request({
      url: apiBaseUrl + url,
      method,
      timeout: 20000,
      header: {
        'content-type': 'application/json',
	      'accessToken': accessToken ? `${accessToken}:${APP_ID}`: ''
      },
      data: _data,
      success: (res: any) => {
	      responseData = res.data
        if (responseData.status === 0) {
	        responseData = res.data;
	        resolve(responseData);
        } else {
		      reject({errno: -1, errmsg: responseData.msg});
        }
      },
      fail: () => {
        reject({
          errno: -1,
          errmsg: '网络不给力，请检查你的网络设置~'
        });
      }
    });
  });
}

const http = {
	get: <T>(api: string, params?: any) =>
			baseRequest('GET', api, {
			...getCommonParams(),
			...params ? params.params ? params.params : params : {}
			}) as Http.Response<T>,
	post: <T>(api: string, params: any) =>
			baseRequest('POST', api, {
				...getCommonParams(),
				...params ? params.params ? params.params : params : {}
			}) as Http.Response<T>,
	put: <T>(api: string, params: any) =>
			baseRequest('PUT', api, {
				...getCommonParams(),
				...params ? params.params ? params.params : params : {}
			}) as Http.Response<T>
};

export default http;
